package com.tangsm.spring.boot.async.utlis;

import com.google.common.collect.Lists;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * List工具类
 *
 * @author tangsm
 */
public class ListUtil {

    /**
     * List拆分(指定每组多少个)
     *
     * @param size 每组元素个数 (>=1)
     * @return 结果
     */
    public static <T> List<List<T>> splitBySize(List<T> list, int size) {
        if (list == null || list.isEmpty() || size < 1) {
            return Collections.emptyList();
        }
        return Lists.partition(list, size);
    }

    /**
     * List拆分，指定拆分成多少组
     *
     * @param list       原始数据集合
     * @param groupCount 组数
     * @param <T>        元素的类型
     * @return 结果
     */
    public static <T> List<List<T>> splitByCount(List<T> list, int groupCount) {
        if (list == null || list.isEmpty() || groupCount < 1) {
            return Collections.emptyList();
        }

        List<List<T>> result = new ArrayList<>();
        // list元素个数
        int size = list.size();
        // 如果拆分组数大于list元素个数，则组数等于元素个数
        groupCount = Math.min(groupCount, size);
        // 每组元素个数
        int count = size / groupCount;
        // 取余数
        int remain = size % groupCount;

        int last = 0;
        for (int i = 0; i < groupCount; i++) {
            int fromIndex, toIndex;
            if (i < remain) {
                fromIndex = i * (count + 1);
                toIndex = (i + 1) * (count + 1);
            } else {
                fromIndex = last;
                toIndex = last + count;
            }
            last = toIndex;
            result.add(list.subList(fromIndex, toIndex));
        }
        return result;
    }

    public static void main(String[] args) {
        int count = 10;
        List<String> list = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            list.add(i + 1 + "");
        }
        System.out.println("构建list完成");

        List<List<String>> listList1 = splitBySize(list, 2);
        System.out.println("==>listList1:" + listList1.size());

        List<List<String>> listList2 = splitBySize(list, 2);
        System.out.println("==>listList2:" + listList2.size());


        List<List<String>> listList3 = splitByCount(list, 2);
        System.out.println("==>listList3:" + listList3.size());

        List<List<String>> listList4 = splitByCount(list, 2);
        System.out.println("==>listList4:" + listList4.size());
    }
}
